define(['moment', 'JDA'], function (moment, JDA) {
    return ['$scope', '$rootScope', '$mdDialog', 'MMWService', '$filter', '$stateParams', '$timeout', 'config', '$gallery', '$calculater',
        function ($scope, $rootScope, $mdDialog, $MMWService, $filter, $stateParams, $timeout, config, $gallery, $calculater) {
            $scope.init = function(){
                $scope.user_name = config.cache.name;
                $scope.shift_info = config.cache.shift_info;
                $scope.onwork_time = config.cache.onwork_time;
                $scope.type = '0'; //首檢=0, 巡檢=2
                $scope.mode = 'batch'; //single=單筆模式, batch=批次模式
                $scope.tab_mode = 'C'; // 頁籤: C=檢驗項目, P=相片, B=不良原因
                $scope.condition = {
                    op_no : '',
                    op_name: '',
                    op_display : '',
                    machine_no : '',
                    plot_no: ''
                };

                if($stateParams.data){
                    // 20200316 for手機板首巡檢增加productId因應SPC控卡
                    $scope.product_id=$stateParams.data.product_id || '';
                    $scope.machines_length = $stateParams.data.machines_length || 0;
                    $scope.condition.op_no = $stateParams.data.op_no || '';
                    $scope.condition.op_name = $stateParams.data.op_name || '';
                    $scope.condition.machine_no = $stateParams.data.machine_no || '';
                    $scope.condition.plot_no = $stateParams.data.plot_no || '';

                    if($stateParams.data.op_no && $stateParams.data.op_no != ''){
                        if($stateParams.data.op_name && $stateParams.data.op_name != ''){
                            $scope.condition.op_display = $stateParams.data.op_no + ' ('+$stateParams.data.op_name+')';
                        }else{
                            $scope.condition.op_display = $stateParams.data.op_no;
                        }
                        if($stateParams.data.plot_no && $stateParams.data.plot_no != ''){
                            $scope.mode = 'single';
                            $scope.search();
                        }
                    }
                }
            };

            $scope.back = function(){
                if(config.authorizationmode == 1){
                    JDA.closeWindow(); //關閉目前視窗
                } else {
                    $rootScope.changeProgram($stateParams.data.parent, {
                        data: {
                            machine_no: $stateParams.data.machine_no,
                            machines_length: $stateParams.data.machines_length
                        }
                    }, true);
                }
            };

            $scope.favorite = function(callback){
                if(config.setting.OperatingArea==''){
                    $scope.$root.showAlert($filter('translate')('home.msg.report_workstation_empty'));
                    return;
                }
                $MMWService.showQueryListPNIG({
                    page_mode: 4,
                    mode:'M',
                    key:'page_no',
                    header : [
                        {label: $filter('translate')('common.queryList.op_c'), code:'page_no'},
                        {label: $filter('translate')('common.queryList.op_n'), code:'page_name'}
                    ],
                    selectKey:{key:'favourite', true:'1', false:'0'},
                    setCondition:function(conditions){
                        conditions.push({column_name:'B.MASTERNO', query_mode:'0', value:config.setting.OperatingArea, merge_condition_model:'AND' });
                        return conditions;
                    },
                    confirm: function(selectItem, dialog){
                        var content = {
                            master_type: 5,
                            master_no :config.setting.OperatingArea,
                            favourite_qc_op_detail:[]
                        };
                        if(selectItem && selectItem.length>0){
                            selectItem.forEach(function(item){
                                if(item.favourite == '1'){
                                    content.favourite_qc_op_detail.push({op_no:item.page_no});
                                }
                            });
                        }
                        beforeSaveFavorite(content.favourite_qc_op_detail, function(){
                            $MMWService.sendToServer({
                                uri: 'ServicesSTD.Module_SYS.favourite_machine_process',
                                content : content,
                                success : function(data){
                                    dialog.hide();
                                    if(callback)
                                        callback();
                                }
                            });
                        });
                    }
                });
            };

            $scope.changeTab = function(tab_index){
                $scope.status_list.forEach(function(data, index){
                    if(index == tab_index){
                        data.select = true;
                    } else {
                        data.select = false;
                    }
                });
            };

            //查詢 - 作業站開窗
            $scope.loadStationNo = function () {
                $scope.$root.showQueryList({
                    key: 'page_no',
                    header: [
                        {label:$filter('translate')('common.queryList.op_c'), code:'page_no'},
                        {label:$filter('translate')('common.queryList.op_n'), code:'page_name'}
                    ],
                    query: function(conditions, feedback){
                        var content = {
                            page_mode: 4,
                            query_condition_info: []
                        };
                        if(config.setting.OperatingArea != ''){
                            content.query_condition_info.push({column_type:'29', query_mode:'0', value:config.setting.OperatingArea, merge_condition_model:'AND' });
                        }
                        //20180525 modify by 李栋 for mantis#0047129
                        $MMWService.pageNumberInfoGet(
                            {
                                page_mode: 4,
                                query_condition_info:[
                                    {column_name:'B.MASTERNO', query_mode:'0', value:config.setting.OperatingArea, merge_condition_model:'AND' }
                                ]
                            },function(data){
                                var temp = $filter('filter')(data, {favourite:'1'});
                                //var temp = data.page_number_info_get;
                                if(temp && temp.length){
                                    feedback(temp);
                                } else {
                                    $scope.$root.showConfirm($filter('translate')('mobile03.msg.favorite_empty'), function(confirmDialog){
                                        confirmDialog.hide();
                                        $timeout(function(){
                                            $scope.favorite(function(){
                                                $scope.loadStationNo();
                                            });
                                        }, 200);
                                    });
                                }
                            }
                        );
                    },
                    selectCode:$scope.condition.op_no||'',
                    confirm : function(selectItem, dialog){
                        //$scope.inspectionInfo.station_no = selectItem.page_no;
                        $scope.condition.op_display = selectItem.page_no + ' ('+selectItem.page_name+')';
                        $scope.condition.op_no = selectItem.page_no;
                        $scope.condition.op_name = selectItem.page_name;
                        $scope.condition.machine_no = selectItem.page_no;
                        $scope.condition.plot_no = '';
                        $scope.inspectionInfo = undefined;
                        localStorage.setItem(config.appName + '_mobile03_favourite_op_no', JSON.stringify({op_no:$scope.condition.op_no, op_name:$scope.condition.op_name}));
                        dialog.hide();
                    }
                });
            };

            //更改範圍內紅叉綠勾的顯示 20200219 陳韋齊 for #66737
            $scope.InRange=function(item){
                if(item.check_type == 1 && !isNaN(item.reason_value)){
                    if((+item.mini_value) <= (+item.reason_value)
                        && (+item.reason_value) <= (+item.max_value)){
                        return true;
                    } else {
                        return false;
                    }
                } else {
                    return false;
                }
            };

            //查詢 - 生產批複合開窗
            $scope.loadPlotInfo = function () {
                if ($scope.condition.op_no != '') {
                    $scope.$root.showQueryList({
                        key:'page_no',
                        header : [
                            {label:$filter('translate')('common.queryList.plot_no'), code:'page_no'}
                        ],
                        query: function(conditions, feedback){
                            $MMWService.pageNumberInfoGet({
                                page_mode : '3',
                                query_condition_info: [
                                    {column_name:'status', query_mode:'0', value:'0', merge_condition_model:'and'},
                                    {column_name:'status', query_mode:'0', value:'1', merge_condition_model:'and'},
                                    {column_name:'OPNo', query_mode:'2', value:$scope.condition.op_no }
                                ]
                            }, function(itemList){
                                if(itemList.length != 0){
                                    feedback(itemList);
                                }else{
                                    feedback();
                                }
                            });
                        },
                        selectCode: $scope.condition.plot_no||'',
                        confirm: function(selectItem, dialog){
                            dialog.hide();
                            $scope.condition.plot_no = selectItem.page_no;
                            $scope.search();
                        },
                        cancel:function(dialog){
                            dialog.hide();
                        }
                    });
                }
                else {
                    $scope.$root.showAlert($filter('translate')('mobile03.msg.op_no_empty'));
                }
            };

            $scope.addRow = function () {
                $scope.loadInspectionReasonList();
            };

            $scope.removeRow = function (item) {
                for(var index = 0; index < $scope.inspectionInfo.checklist_detail.length; index++){
                    if($scope.inspectionInfo.checklist_detail[index].item_code == item.item_code){
                        $scope.inspectionInfo.checklist_detail.splice(index, 1);
                        break;
                    }
                }
            };

            var badCodeList = [];
            //不良原因開窗
            $scope.loadInspectionReasonList = function (item) {
                $scope.$root.showQueryList({
                    key:'page_no',
                    selectCode:item?item.page_no:'',
                    header : [
                        {label: $filter('translate')('common.queryList.badReason_c'), code:'page_no'},
                        {label: $filter('translate')('common.queryList.badReason_n'), code:'page_name'}
                    ],
                    query: function(conditions, feedback){
                        var list = [];
                        if(badCodeList && badCodeList.length > 0){
                            badCodeList.forEach(function(item){
                                var isChosen = false;
                                for(var i = 0; i < $scope.inspectionInfo.checklist_detail.length; i++){
                                    // 不顯示已選擇的不良原因
                                    if($scope.inspectionInfo.checklist_detail[i].item_code == item.page_no){
                                        isChosen = true;
                                        break;
                                    }
                                }
                                if(!isChosen){
                                    list.push(item);
                                }
                            });
                        }
                        feedback(list);
                    },
                    confirm: function (selectItem, radioDialog) {
                        if(item != undefined){
                            item.item_code = selectItem.page_no;
                            item.page_no = selectItem.page_no;
                            item.page_name = selectItem.page_name;
                        } else {
                            $scope.inspectionInfo.checklist_detail.push({
                                item_code: selectItem.page_no,
                                page_no : selectItem.page_no,
                                page_name : selectItem.page_name,
                                item_qty: 1,
                                item_seq: ''
                            });
                        }
                        radioDialog.hide();
                    }
                });
            };

            var picLimitNum = 5;
            $scope.picSrcArray = [];
            //拍照
            $scope.pic_add = function($event){
                if($scope.picSrcArray.length < picLimitNum){
                    if(typeof(navigator.camera) !== 'undefined'){
                        //回傳URI
                        navigator.camera.getPicture(
                            function(imageURI) {
                                
                                if($rootScope.compressImage)
                                {
                                    $rootScope.compressImage(imageURI, 
                                        function(data){  
                                            $scope.picSrcArray.push(data);
                                            $scope.$apply();
                                            }); 
                                }
                                else
                                {
                                    $scope.picSrcArray.push(imageURI);
                                    $scope.$apply();
                                }
                                //$scope.data.scrollLeft = document.getElementById('img-tile-list').clientWidth;
                            },
                            function(message) {
                                //alert('Failed because: ' + message);
                            },
                            {
                                quality: 50,
                                destinationType: Camera.DestinationType.DATA_URL
                            }
                        );
                    } else if(window.nodeRequire){
                        //回傳URI
                        $scope.$root.FileDialog({
                            callback:function(fileList){
                                $scope.$root.showLoading();
                                $scope.$apply();
                                setTimeout(function(){
                                    if(fileList){
                                        if(fileList.length == 0){
                                            //
                                        } else if(($scope.picSrcArray.length + fileList.length) > picLimitNum){
                                            $scope.$root.showAlert($filter('translate')('B0501.msg.pic_limit', {num:picLimitNum}));
                                        } else {
                                            var fs = window.nodeRequire('fs');
                                            fileList.forEach(function(fileName){
                                                var image = fs.readFileSync(fileName);
                                                if(image)
                                                {                
                                                    if($rootScope.compressImage)
                                                    {
                                                        $rootScope.compressImage(new Buffer(image).toString('base64'), 
                                                        function(data){$scope.picSrcArray.push(data)}); 
                                                    }
                                                    else
                                                    {
                                                        $scope.picSrcArray.push(new Buffer(image).toString('base64'))
                                                    }
                                                }
                                            });
                                        }
                                    }
                                    $scope.$root.hideLoading();
                                    $scope.$apply();
                                });
                            }
                        });
                    } else {
                        $scope.$root.showAlert($filter('translate')('common.msg.cant_use_camera'));
                    }
                } else {
                    $scope.$root.showAlert($filter('translate')('B0501.msg.pic_limit', {num:picLimitNum}));
                }
            };

            $scope.pic_delete = function(index){
                $scope.picSrcArray.splice(index,1);
            };

            $scope.pic_open = function(index){
                $gallery.show('#'+(index+1), 'data:image/jpeg;base64,'+$scope.picSrcArray[index], function(){});
            };

            $scope.open_checkPic = function(item){
                $gallery.show(item.reason_no, $scope.server_url+item.picture_path, function(){});
            };

            //查詢 - 確認
            $scope.search = function () {
                if ($scope.isPlotAndOpEmpty()) {
                    $scope.$root.showAlert($filter('translate')('mobile03.msg.plot_no_empty'));
                } else {
                    //20180525 modify by 李栋 for mantis#0047129
                    $MMWService.pageNumberInfoGet({
                        page_mode : '15',
                        query_condition_info : [
                            {column_name:'OPNo', query_mode:'0', value: $scope.condition.op_no }
                        ]
                    }, function(itemList){
                        badCodeList = itemList;
                        $scope.inspectionInfo = {};
                        $scope.inspectionInfo.check_time = new Date();

                        wip_plot_status_info_get({
                            plot_no:$scope.condition.plot_no,
                            op_no:$scope.condition.op_no
                        }, function(data){
                            $scope.inspectionInfo.qty = data.qty;
                            $scope.inspectionInfo.employee_no = config.cache.account;
                            $scope.inspectionInfo.legal_employee_no = true;
                            $scope.inspectionInfo.check_qty = 1;
                            $scope.inspectionInfo.area_no = data.area_no;
                            opqcreason_info_get({plot_no:$scope.condition.plot_no,op_no:$scope.condition.op_no}, function(data){
                                $scope.server_url = 'http://'+config.server.ip+':'+config.server.port;
                                //$scope.inspectionInfo.type = data.type;
                                $scope.inspectionInfo.area_no = data.area_no;
                                $scope.inspectionInfo.qc_reason_detail = data.qc_reason_detail||[];
                                $scope.inspectionInfo.checklist_detail = [];
                                $scope.tab_mode = 'C';
                            });
                        });
                    });
                }
            };

            $scope.confirm = function () {
                if ($scope.isPlotAndOpEmpty()) {
                    $scope.$root.showAlert($filter('translate')('mobile03.msg.plot_no_empty'));
                }else{
                    var defect_qty = 0, msg = '';
                    //20200831 modify by Dustdusk for M#77210:
                    $scope.inspectionInfo.qc_reason_detail.forEach(function(item, index){
                        //此項目須判斷是否要輸入不良
                        // 20231221 modify by wenwei for M#153794: [MSSQL] [H5][首巡自末检]质量检验检验项目不合格是否需要录入不良问题
                        if(item.is_inputscrap == '1'){
                            // switch btn 沒選過 / false
                            if(item.check_type == 0 && (item.reason_value == '' || item.reason_value == 'false')){
                                // 檢查不良現象是否有新增不良原因
                                if(dialog.inspectionInfo.checklist_detail.length == 0){
                                    msg += $filter('translate')('B0207.check_list.column1') + item.reason_no + '、';
                                }
                            } else if(item.check_type == 1){
                                // 有輸入值
                                if(item.reason_value !== '' && item.reason_value !== null) {
                                    // 符合標準
                                    if((+item.mini_value) <= (+item.reason_value) && (+item.reason_value) <= (+item.max_value)) return
                                }
                                // 檢查不良現象是否有新增不良原因
                                if(dialog.inspectionInfo.checklist_detail.length == 0){
                                    msg += $filter('translate')('B0207.check_list.column1') + item.reason_no + '、';
                                }
                            }
                        }
                    });

                    if(msg != ''){
                        if($scope.inspectionInfo.checklist_detail.length == 0){
                            $scope.$root.showAlert(msg + $filter('translate')('mobile03.msg.checkitem_need_badreason'));
                            return;
                        }
                    }

                    $scope.inspectionInfo.checklist_detail.forEach(function(item, index){
                        item.item_seq = index;
                        defect_qty = $calculater.decimalAdd(defect_qty, item.item_qty);
                    });

                    if ((+defect_qty) > (+$scope.inspectionInfo.check_qty)){
                        msg = $filter('translate')('mobile03.msg.check_qty_lt_defect_qty');
                    } else if($scope.inspectionInfo.legal_employee_no == false){
                        msg = $filter('translate')('mobile03.msg.check_employee_error');
                    }

                    if (msg == ''){
                        $scope.inspectionInfo.defect_qty = defect_qty;
                        firstPieceCheckProcess();
                    } else {
                        $scope.$root.showAlert(msg);
                    }
                }
            };

            $scope.isPlotAndOpEmpty = function(){
                var isEmpty = false;
                if ($scope.condition.op_no.length == 0 || $scope.condition.plot_no.length == 0) {
                    isEmpty = true;
                }
                return isEmpty;
            };

            // function init(){
            //     getUserInfo(config.cache.account, function(data){
            //         $scope.user_name = config.cache.name = data.employee_name;
            //         $scope.machines = [];
            //         if(data.shift != 'N\\A'){
            //             $scope.shift_info = config.cache.shift_info = $filter('translate')('mobile03.shift_info', {
            //                 shift:data.shift,
            //                 start_time:moment(data.shift_start_date).format('HH:mm'),
            //                 end_time:moment(data.shift_end_date).format('HH:mm'),
            //             });
            //         } else {
            //             $scope.shift_info = config.cache.shift_info = $filter('translate')('mobile03.shift_info', {
            //                 shift:data.shift,
            //                 start_time:'00:00',
            //                 end_time:'00:00',
            //             });
            //         }
            //         $scope.onwork_time = config.cache.onwork_time = '08:15';
            //         FavouriteMachineInfoGet(config.cache.account, function(){});
            //     });
            // }

            // function getUserInfo(userCode, callback){
            //     $MMWService.sendToServer({
            //         uri : 'ServicesSTD.Module_SYS.user_information_get',
            //         content : {
            //             employee_no : userCode,
            //             report_datetime:moment(new Date()).format('YYYY-MM-DD HH:mm:ss'),
            //             machine_no:'A',
            //             return_type : '00'
            //         },
            //         success : function(data){
            //             if(callback)
            //                 callback(data);
            //         }
            //     });
            // }

            function beforeSaveFavorite(favoriteList, callback){
                var isDeleteCurrentOp = false;
                if($scope.condition.op_no && $scope.condition.op_no != ''){
                    if(favoriteList && favoriteList.length > 0){
                        var filterList = $filter('filter')(favoriteList, {op_no: $scope.condition.op_no}, true);
                        if(filterList.length == 0){
                            isDeleteCurrentOp = true; //使用者將"目前的作業站"從我的最愛移除了
                        }
                    }
                }

                if(isDeleteCurrentOp){
                    $scope.$root.showAlert($filter('translate')('mobile03.msg.favorite_remove'),function(){
                        $scope.condition.op_no = '';
                        $scope.condition.op_name = '';
                        $scope.condition.machine_no = '';
                        $scope.condition.op_display = '';
                        $scope.condition.plot_no = '';
                        $scope.inspectionInfo = undefined;
                        localStorage.setItem(config.appName + '_mobile03_favourite_op_no', JSON.stringify({op_no:$scope.condition.op_no, op_name:$scope.condition.op_name}));
                        if(callback)
                            callback();
                    });
                }else{
                    if(callback)
                        callback();
                }
            }

            function wip_plot_status_info_get(content, feedback){
                $MMWService.sendToServer({
                    uri: 'ServicesSTD.Module_WIP.wip_plot_status_info_get',
                    content: content,
                    success: function (data) {
                        // data = JSON.parse(data.Result);
                        if(data.details && data.details.length > 0){
                            if(feedback)
                                feedback(data.details[0]);
                        } else {
                            $scope.inspectionInfo = undefined;
                            $scope.$root.showAlert($filter('translate')('common.msg.no_data'));
                        }
                    }
                });
            }

            function opqcreason_info_get(content, feedback){
                $MMWService.sendToServer({
                    uri: 'ServicesSTD.Module_WIP.op_qcreason_info_get',
                    content: {
                        op_no: content.op_no,
                        lot_no: content.plot_no,
                        machine_no: '',
                        area_no: '',
                        type: $scope.type
                    },
                    success: function (data) {
                        if(feedback)
                            feedback(data);
                    }
                });
            }

            //送出結果
            function firstPieceCheckProcess() {
                var content = {
                    machine_no: moment(new Date()).format('YYYYMMDDHHmmss'),
                    station_no: $scope.condition.op_no,
                    op_no: $scope.condition.op_no,
                    plot_no: $scope.condition.plot_no,
                    employee_no: $scope.inspectionInfo.employee_no,
                    productid:$scope.product_id,
                    area_no: $scope.inspectionInfo.area_no,
                    check_qty: $scope.inspectionInfo.check_qty,
                    defect_qty: $scope.inspectionInfo.defect_qty,
                    check_time: moment($scope.inspectionInfo.check_time).format('YYYY-MM-DD HH:mm:ss'),
                    qc_result: 'Y',
                    // 20200327 modify by WeiTing for M#67647 - 因為 SPC檢驗的關係，改成要傳給後台 qc_type 等於 -1 或 -2 才能走原本標準版的流程。
                    qc_type: '-1', //首檢qc_type=-1, 巡檢qc_type=-2
                    type: $scope.type,
                    checklist_detail: $scope.inspectionInfo.checklist_detail,
                    image_detail: [],
                    qc_reason_detail: $scope.inspectionInfo.qc_reason_detail,
                    run_type: 1 // run_type=0：一開始判斷要走SPC還是標準版帶 0 ; run_type=1：SPC檢驗和標準版檢驗送回資料帶 1。
                };

                if((+content.defect_qty) != 0)
                    content.qc_result = 'N';

                for(var i=0;i<$scope.picSrcArray.length;i++){
                    var picSrc = $scope.picSrcArray[i];
                    content.image_detail.push({
                        image_src:picSrc,
                        image_seq:i,
                        image_format:'jpg'
                    });
                }

                $MMWService.sendToServer({
                    uri: 'ServicesSTD.Module_WIP.first_piece_check_process',
                    content: content,
                    success: function () {
                        //20180416 modify by 李栋 for mantis#0045407
                        $scope.$root.showToast($filter('translate')('common.msg.success'));
                        if($scope.mode == 'single'){
                            $scope.back();
                        }else{
                            $scope.inspectionInfo.check_time = new Date();
                            $scope.inspectionInfo.checklist_detail = []; //清除不良原因
                            $scope.picSrcArray = []; //清除相片
                            $scope.inspectionInfo.qc_reason_detail.forEach(function(item){
                                item.reason_value = '';
                            });
                        }
                    }
                });
            }
        }
    ];
});
